#!/user/bin/python
# -*- coding: utf-8 -*-
'''
 @Time    : 2018/5/20 15:58
 @File    : crawler_task_service.py
 @desc    :
'''
from commonSpiders.creeper.manager import CRAWLER_PROCESS_MANAGER_DICT_KEY
from commonSpiders.creeper.net.msg import CreeperFailure, CreeperSuccessMsg
from commonSpiders.creeper.service.service_base import ClientBaseService
from commonSpiders.net.extend_context import ContextExtend
from commonSpiders.utils.singleton import singleton

CLIENT_CRAWLER_TASK_SERVICE_KEY = 'client_crawler_task_service'


@singleton
@ContextExtend.extend(CLIENT_CRAWLER_TASK_SERVICE_KEY)
class CrawlerTaskService(ClientBaseService):

    TASK_CONTEXT = 'TASK_CONTEXT'

    '''
    爬虫任务服务
    '''
    def __init__(self):
        pass

    def start_task(self, data):
        '''

        :param data:
        :return:
        '''
        manager_guid = data['data'].get('manager_guid', '')
        task_info = data['data'].get('task_info', '')
        self.context.setdefault(self.TASK_CONTEXT, {})
        self.context.setdefault(CRAWLER_PROCESS_MANAGER_DICT_KEY, {})
        manager = self.context[CRAWLER_PROCESS_MANAGER_DICT_KEY].get(manager_guid, None)
        if manager:
            try:
                msg = manager.start_task(task_info)
                # 存储任务信息
                self.context[self.TASK_CONTEXT].setdefault(task_info.task_id, manager_guid)
                msg = CreeperSuccessMsg(manager_guid=manager.guid, msg=msg)
            except Exception as e:
                msg = CreeperFailure(error=e.message)
        else:
            msg = CreeperFailure(error='没有找到爬虫进程管理器')
        return msg

    def pause_task(self, data):
        '''
        task_id
        :param data:
        :return:
        '''
        task_id = data.get('task_id')

    def resume_task(self, data):
        '''
        task_id
        :param data:
        :return:
        '''
        task_id = data.get('task_id')

    def stop_task(self, data):
        '''
        task_id
        :param data:
        :return:
        '''
        task_id = data.get('task_id')